<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>任务列表</title>
  <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
  <link href="../../../css/mui.min.css" rel="stylesheet" />
  <link href="../css/common.css" rel="stylesheet" />
  <style>
    .mui-card {
      border-radius: 5px;
      box-shadow: none;
    }

    .lists {
      padding: 20px;
    }

    .lists li {
      margin-bottom: 10px;
    }

    .lists li:last-child {
      margin: 0;
    }

    .lists li .left_name {
      color: #9098AB;
      white-space: nowrap;
    }

    .lists li .right_name {
      color: #333333;
      float: right;
    }

    .btntxt {
      font-size: 14px;
      padding-right: 20px;
      color: #3188FE;
    }

    .mui-navigate-right:after,
    .mui-push-right:after {
      right: 15px;
      color: #999999;
      font-size: 18px;
    }

    .tag {
      display: inline-block;
      width: 55px;
      height: 20px;
      line-height: 20px;
      transform: skewX(-15deg);
      text-align: center;
      color: #FFFFFF;
    }
  </style>
</head>

<body>
  <div id="container">
    <header class="mui-bar mui-bar-nav">
      <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left text-white"></a>
      <h1 class="mui-title">任务列表</h1>
    </header>
    <div id="refreshContainer" class="mui-scroll-wrapper mui-content">
      <div class="mui-scroll">
        <div>
          <div class="mui-card card_content" v-for="item in list" :key="item.id" @tap="toTotal(item)" v-cloak>
            <div class="mui-card-content">
              <ul class="mui-table-view lists">
                <li class="lis mui-navigate-right">
                  <span :class="['tag', status(item.ss, 1)]">{{status(item.ss, 0)}}</span>
                  <span>{{item.n}}</span>
                </li>
                <li class="lis color-999 text-sm">
                  <span>开始时间：{{formatDate(item.st)}}</span>
                </li>
                <li class="lis color-999 text-sm">
                  <span>结束时间：{{formatDate(item.et)}}</span>
                </li>
              </ul>
            </div>
            <div class="mui-card-footer">
			  <div>
				  <span class="btntxt" @tap.stop="offlineData(item.id)" style="color: #333333;">缓存数据</span>
				  <span class="btntxt" @tap.stop="getDel(item.id)" style="color: #333333;">删除</span>
			  </div>
              <a class="btntxt" v-if="item.showClaim == 1 && item.claimed == 0" @tap.stop="claim(item)">领取任务</a>
			  
            </div>
          </div>
        </div>

      </div>
    </div>
  </div>

  <script src="../../../js/mui.js"></script>
  <script src="../../../js/jquery-1.7.2.min.js"></script>
  <script src="../js/mkeyplus.base.js" type="text/javascript" charset="utf-8"></script>
  <script src="../../../js/vue.js" type="text/javascript" charset="utf-8"></script>
  <script src="../js/indexDBs.js"></script>
  <script type="text/javascript">
    mui.init({
      pullRefresh: {
        container: "#refreshContainer", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
        down: { //下拉刷新
          style: 'circle',
          height: 50, //可选,默认50.触发下拉刷新拖动距离,
          auto: false, //可选,默认false.首次加载自动下拉刷新一次
          contentdown: "下拉可以刷新", //可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
          contentover: "释放立即刷新", //可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
          contentrefresh: "正在刷新...", //可选，正在刷新状态时，下拉刷新控件上显示的标题内容
          callback: async function () { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
            vm.form.page = 1;
            vm.getList();
            mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
          }
        },
        up: { //上拉加载
          height: 50, //可选.默认50.触发上拉加载拖动距离
          auto: false, //可选,默认false.自动上拉加载一次
          contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
          contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
          callback: async function () { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
            vm.getList();
          }
        }
      }
    })
    let lineType = null;
    let ids = 1;
    var db = {};
    const dbName = 'myDBcheck';
    const storeName = 'verifyList';
    if (window.plus) {
      plusready();
    } else {
      document.addEventListener('plusready', plusready, false);
    }

    async function plusready () {
      var self = plus.webview.currentWebview();
      // vm.form.projectId = self.projectId
      vm.lineType = getSysInfo();
      lineType = getSysInfo();
      // const dbName = 'myDB', storeName = 'processPackage'
      await openDB(dbName, storeName, 1).then(res => {
        console.log('111', res)
        db = res
        // return res
      })
      if (!lineType) {
        getLineData()
        return
      }
      vm.getList()

    }

    let vm = new Vue({
      el: "#container",
      data: {
		projectId: 0,
        form: {
          page: 1,
          size: 20,
          //stage: 5,
          //projectId: '',
          //projectCategory: 0
        },
        lineType: null,
        list: []
      },
      created: function () { },
      methods: {
        getList () {
          if (this.form.page == 1) {
            plus.nativeUI.showWaiting('加载中')
          }
          mui.baseApp.httpRequst('get', '/app/api/check/task', this.form, (data) => {
            plus.nativeUI.closeWaiting()
            let list = this.list
            if (this.form.page == 1) { //第一页下拉
              mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
              list = data.records
            } else {
              list = list.concat(data.records)
            }
            this.list = list
            this.form.page++
            let datas = {
              id: this.projectId,
              records: [...list] || []
            }
            getSearchData(datas)
            if (data.records.length < this.form.size) {
              mui('#refreshContainer').pullRefresh().enablePullupToRefresh();
              mui("#refreshContainer").pullRefresh().endPullupToRefresh(true); //参数为true代表没有更多数据了。
            } else {
              mui("#refreshContainer").pullRefresh().endPullupToRefresh(false); //参数为true代表没有更多数据了。
            }
          })
        },
        status (status, type) {
          if (type == 0) {
            if (status == 0) {
              return '未开始'
            } else if (status == 1) {
              return '确认中'
            } else {
              return '已确认'
            }
          } else if (type == 1) {
            if (status == 0) {
              return 'bg-blue'
            } else if (status == 1) {
              return 'bg-green'
            } else {
              return 'bg-gray'
            }
          }

        },
        formatDate (tmp, fmt) {
          return mui.baseApp.formatDate(tmp, fmt)
        },
        toTotal (item) {
          // projectCategory  项目分类，0:常规项目 1:单任务项目
          // taskTotal.html 任务总览
          if (item.claimed == 0 && item.showClaim == 1) {
            mui.toast('请先领取任务，再进行操作')
            return
          }
          mui.baseApp.openWindow('./detail.html', {
            projectTaskId: item.id,
            projectCategory: 0
          })
        },
        claim (row) {
          let self = this
          mui.confirm("是否领取本次验收任务 ，其它成员将无法操作", "提示", ["取消", "确认"], function (e) {
            if (e.index) {
              plus.nativeUI.showWaiting('加载中')
              mui.baseApp.httpRequst('post', '/app/api/check/claimTask/' + row.id, {}, (data) => {
                plus.nativeUI.closeWaiting()
                mui.toast("领取成功")
                self.form.page = 1
                self.getList()
                self.toTotal(row)
              }, (err) => {
                plus.nativeUI.closeWaiting()
              })
            }
          })
        },
		// 离线数据删除
		getDel(id){
		    deleteDB(db, storeName, id).then(res=>{
				if(res.isTrusted){
					mui.toast('缓存数据删除成功')
				}
			})
		},
		// 离线数据缓存
		offlineData(projectTaskId){
		  plus.nativeUI.showWaiting('离线数据下载中...')
		  mui.baseApp.httpRequst(
		    "get",
		    "/app/api/check/offline/data/"+projectTaskId,
		    {},
		    function (data) {
			  plus.nativeUI.closeWaiting()
		      data.data['isOver']= false
		      data.data['id'] = projectTaskId
		      console.log('离线数据1122',data)
		      let datas = data.data
		      getSearchData(datas)
		    },
		    function () {
		      plus.nativeUI.closeWaiting()
		      console.log("获取数据失败")
		    }
		  )
		}
      },
    })
	
    function getLineData () {
      getDataByKey(db, storeName, vm.projectId).then(res => {
        plus.nativeUI.closeWaiting();
        console.log('获取离线数据', JSON.stringify(res))
        let data = res
        let list = vm.list
        if (vm.form.page == 1) { //第一页下拉
          mui('#refreshContainer').pullRefresh().endPulldownToRefresh();
          list = data.records
        } else {
          list = list.concat(data.records)
        }
        vm.list = list
        vm.form.page++
        if (data.records.length < vm.form.size) {
          mui('#refreshContainer').pullRefresh().enablePullupToRefresh();
          mui("#refreshContainer").pullRefresh().endPullupToRefresh(true); //参数为true代表没有更多数据了。
        } else {
          mui("#refreshContainer").pullRefresh().endPullupToRefresh(false); //参数为true代表没有更多数据了。
        }
      })
    }
    function getSearchData (data) {
      //通过游标
      cursorGetData(db, storeName).then(res => {
        console.log('获取缓存', res)
        if (res.length > 0) {
          let arr = res.find(msg => {
            //console.log('3331', msg.id)
            return data.id == msg.id
          })
          //console.log('333获取缓存', arr)
          if (arr) {
            getUpData(data)
          } else {
            getLineAdd(data)
          }
          //console.log('333100', arr)
        } else {
          // getUpData(data)
          getLineAdd(data)
        }

      }).catch(function (error) {
        console.log(error);
      })
    }
    function getLineAdd (data) {
      console.log('add', data)
      addData(db, storeName, data).then(res => {
        console.log('add数据', res)
        mui.toast('数据缓存成功')
      }).catch(function (error) {
		console.log(error);
	  })
    }
    function getUpData (data) {
      updateDB(db, storeName, data)
    }
    function getSysInfo() {
	  // return false
      types = {};
      types[plus.networkinfo.CONNECTION_UNKNOW] = "未知";
      types[plus.networkinfo.CONNECTION_NONE] = "未连接网络";
      types[plus.networkinfo.CONNECTION_ETHERNET] = "有线网络";
      types[plus.networkinfo.CONNECTION_WIFI] = "WiFi网络";
      types[plus.networkinfo.CONNECTION_CELL2G] = "2G蜂窝网络";
      types[plus.networkinfo.CONNECTION_CELL3G] = "3G蜂窝网络";
      types[plus.networkinfo.CONNECTION_CELL4G] = "4G蜂窝网络";

      var str = types[plus.networkinfo.getCurrentType()];
      if (str == '未知' || str == '未连接网络') {
        return false;
      } else {
        return true;
      }

    }
    window.addEventListener('back', function (event) {
      let data = event.detail
      vm.form.page = 1
      vm.getList()
    });
  </script>
</body>

</html>